import IconFont from '@/components/IconFont';
import { doFetch } from '@/utils/doFetch';
import { DeleteOutlined, LoadingOutlined } from '@ant-design/icons';
import { message, theme, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import { useState } from 'react';
import './index.less';

const beforeUpload = (file) => {
  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/png' ||
    file.type === 'image/jpg' ||
    file.type === 'image/svg' ||
    file.type === 'image/gif';
  if (!isJpgOrPng) {
    message.error('仅可以上传 JPG/PNG/GIF/JPEG/SVG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片必须小于 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

const Bglight = ({ currentUser, refresh, pkey }) => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState(currentUser?.[pkey]);
  let token = localStorage.getItem('TOKENES');

  const {
    token: { colorBgThird, colorText, colorBgSecondary, colorPrimary },
  } = theme.useToken();

  const handleChange = async (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      const { response } = info.file;
      const data = response?.data?.dataList?.[0]?.url ?? null;
      // 更新用户信息接口
      let res = await doFetch({
        url: '/system/user',
        params: {
          [pkey]: data,
        },
        method: 'PUT',
      });
      if (res.code === 0) {
        setLoading(false);
        setImageUrl(data);
        await refresh();
      }
    }
  };

  const title = pkey === 'bgUrlDark' ? '夜间模式背景图' : '背景图片';

  const uploadButton = (
    <div
      className="hoverabler"
      style={{
        position: 'relative',
        background: colorBgThird,
        backgroundSize: '68%',
        width: '100%',
        height: '88%',
        borderRadius: 12,
        color: colorText,
      }}
    >
      {loading ? (
        <div
          className="center"
          style={{
            position: 'absolute',
            width: '100%',
            height: '100%',
            borderRadius: 8,
          }}
        >
          <LoadingOutlined style={{ color: colorText }} />
        </div>
      ) : (
        <div
          className="masks"
          style={{
            position: 'absolute',
            width: '100%',
            height: '100%',
            borderRadius: 8,
            width: '92%',
            height: '90%',
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
            margin: 'auto',
            backgroundColor: colorBgSecondary,
            zIndex: 1000,
            backdropFilter: 'blur(2px)',
            opacity: 0.5,
          }}
        >
          <IconFont type="icon-camera" style={{ fontSize: 26, marginBottom: 12 }}></IconFont>
          <span>上传{title}</span>
        </div>
      )}
    </div>
  );

  const UploadImage = ({ src }) => (
    <div
      className="hoverabler"
      style={{
        position: 'relative',
        backgroundSize: 'contain',
        background: colorBgThird,
        width: '100%',
        height: '88%',
        borderRadius: 12,
      }}
    >
      {src && (
        <div
          className="center"
          style={{
            position: 'absolute',
            width: '100%',
            height: '100%',
            borderRadius: 8,
          }}
        >
          <img
            src={src}
            alt=""
            style={{
              borderRadius: 8,
              width: '100%',
              height: '100%',
              objectFit: 'cover',
            }}
          />
        </div>
      )}
      <div
        className="mask"
        style={{
          position: 'absolute',
          width: '92%',
          height: '90%',
          left: 0,
          right: 0,
          top: 0,
          bottom: 0,
          margin: 'auto',
          borderRadius: 8,
          backgroundColor: colorBgSecondary,
          zIndex: 1000,
          backdropFilter: 'blur(2px)',
        }}
      >
        <IconFont type="icon-camera" style={{ fontSize: 26, marginBottom: 12 }}></IconFont>
        <span>上传{title}</span>
      </div>
    </div>
  );

  return (
    <div className="diystyles center" style={{ color: colorText }}>
      <div className="spread" style={{ width: '100%' }}>
        <span style={{ alignSelf: 'flex-start', opacity: 0.5 }}>{title}</span>
        <DeleteOutlined
          style={{ color: colorPrimary }}
          onClick={async () => {
            let res = await doFetch({
              url: '/system/user',
              params: {
                [pkey]: "-1",
              },
              method: 'PUT',
            });
            if (res.code === 0) {
              setImageUrl(null);
              await refresh();
            }
          }}
        />
      </div>
      <ImgCrop
        rotationSlider
        showGrid
        showReset
        quality={1}
        modalTitle="编辑背景"
        cropShape={'rect'} //裁切区域形状，'rect' 或 'round'
        aspect={16 / 9} //裁切区域宽高比，width / height
        beforeCrop={(file) => {
          if (file.type !== 'image/gif') {
            return true;
          }
        }}
      >
        <Upload
          name="file"
          listType="picture-circle"
          className="avatar-uploader"
          showUploadList={false}
          action={REACT_APP_URL + '/file/upload'}
          beforeUpload={beforeUpload}
          onChange={handleChange}
          headers={{ token }}
        >
          {imageUrl ? <UploadImage src={imageUrl} /> : uploadButton}
        </Upload>
      </ImgCrop>
    </div>
  );
};
export default Bglight;
